package test.socket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端 全双工 但同时只能连接一台服务器
 */
public class BIOClient {
	private Socket socket;
	private InputStream in;
	private OutputStream out;

	/**
	 * 启动客户端需要指定地址和端口号
	 */
	private BIOClient(String address, int port) {
		try {
			socket = new Socket(address, port);
			this.in = socket.getInputStream();
			this.out = socket.getOutputStream();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//System.out.println("客户端启动成功");
	}

	public void start() {
		// 和服务器不一样，客户端只有一条连接，能省很多事
		Reader reader = new Reader();
		Writer writer = new Writer();
		reader.start();
		writer.start();
	}

	public void close() {
		try {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			if (socket != null) {
				socket.close();
			}
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private class Reader extends Thread {
		private InputStreamReader streamReader = new InputStreamReader(in);
		private BufferedReader reader = new BufferedReader(streamReader);

		@Override
		public void run() {
			try {
				String line = "";
				while (!socket.isClosed() && line != null && !"exit".equals(line)) {
					line = reader.readLine();
					if (line != null) {
						System.out.println("Server: " + line);
					}
				}
				System.out.println("服务器主动断开连接");
				close();
			} catch (IOException e) {
				System.out.println("连接已断开");
			} finally {
				try {
					if (streamReader != null) {
						streamReader.close();
					}
					if (reader != null) {
						reader.close();
					}
					close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private class Writer extends Thread {
		private PrintWriter writer = new PrintWriter(out);
		private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

		@Override
		public void run() {
			try {
				String line = "";
				while (!socket.isClosed() && line != null && !"exit".equals(line)) {
					line = reader.readLine();
					if ("".equals(line)) {
						System.out.print("发送的消息不能为空");
					} else {
						writer.println(line);
						writer.flush();
					}
				}
				System.out.println("客户端退出");
				close();
			} catch (IOException e) {
				System.out.println("error:连接已关闭");
			} finally {
				try {
					if (writer != null) {
						writer.close();
					}
					if (reader != null) {
						reader.close();
					}
					close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {

		new BIOClient("127.0.0.1", 808).start();
	}
}